#include "videostream.h"

VideoStream::VideoStream(Video_Params& video_param):m_params(video_param)
{
	if (m_params.video_mode == "online")
	{
		mode = 0;
		m_rtsp = std::make_unique<Rtsp>(m_params.video_source);
	}
	else
	{
		mode = 1;
		if (!m_videocapture.open(m_params.video_source))
		{
			std::cerr << "Can't open " << m_params.video_source << std::endl;
			return;
		}
		m_videocapture.set(cv::CAP_PROP_POS_FRAMES, m_params.m_startFrame);
		frame_cnt = m_params.m_startFrame;
		m_params.m_fps = m_videocapture.get(cv::CAP_PROP_FPS);
		video_param.m_fps = m_params.m_fps;
	}
}

cv::Mat VideoStream::read_one_frame()
{
	cv::Mat frame;
	if (mode == 0)
	{
		++frame_cnt;
		frame = m_rtsp->GetMatData();
	}
	else
	{
		if (m_params.m_endFrame>0 && frame_cnt > m_params.m_endFrame)
			return cv::Mat();
		++frame_cnt;
		if (!m_videocapture.read(frame))
		{
			std::cerr << "can not read frame from video" << std::endl;
			return cv::Mat();
		}
	}

	if (m_params.rotate >= 0 && !frame.empty())
		cv::rotate(frame, frame, m_params.rotate);

	//for test
	//frame = imread("test.jpg");

	return frame;
}